package com.tools.web.interceptor.quota;

import com.tools.common.object.Note;

/**
 * 使用 Redis 实现配额限制拦截器的 Lua 脚本接口
 * */
@Note("使用 Redis 实现配额限制拦截器的 Lua 脚本接口")
public interface QuotaRedisLuaScript {

    String CHECK_ALLOW =
            "local key = KEYS[1]" +
            "local allow = tonumber(ARGV[1])" +
            "local value = redis.call('GET', key)" +
            "if value == false then" +
            "   return 1" +
            "else" +
            "   local numValue = tonumber(value)" +
            "   if numValue < allow then" +
            "       return 1" +
            "   else" +
            "       return 0" +
            "   end" +
            "end";

    String INCREASE =
            "local key = KEYS[1]" +
            "local expiration = tonumber(ARGV[1])" +
            "local value = redis.call('GET', key)" +
            "if value == false then" +
            "   redis.call('SETEX', key, expiration, 1)" +
            "   return 1" +
            "else" +
            "   local quotaCount = tonumber(value) + 1" +
            "   local ttl = redis.call('TTL', key)" +
            "   if ttl <= 0 then" +
            "       redis.call('SETEX', key, expiration, quotaCount)" +
            "       return 1" +
            "   else" +
            "       redis.call('SETEX', key, ttl, quotaCount)" +
            "       return 1" +
            "   end" +
            "end";
}
